package com.sky.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.AdressProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class GaodeUtils {
    @Autowired
    private AdressProperties adressProperties;

//https://restapi.amap.com/v3/direction/walking?origin=116.434307,39.90909&destination=116.434446,39.90816&key=<用户的key>
    public static final String GD_URL = "https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s";
    public static final String DIS_URL = "https://restapi.amap.com/v3/distance?key=b81c9a1ae3a0ef1f944a44338d6ed23c&origins=";
    private static final String KEY = "b81c9a1ae3a0ef1f944a44338d6ed23c";
    private static final String SUCCESS_FLAG = "1";

    /**
     * 根据地址获取对应的经纬度信息
     */
    public static String getLonAndLatByAddress(String address) {
        String formattedUrl = String.format(GD_URL, address, KEY);
        JSONObject responseJson = fetchJsonFromUrl(formattedUrl);

        validateResponseStatus(responseJson);

        JSONArray geocodesArray = responseJson.getJSONArray("geocodes");
        if (geocodesArray == null || geocodesArray.isEmpty()) {
            throw new RuntimeException("未找到与地址匹配的经纬度信息。");
        }

        return geocodesArray.getJSONObject(0).getString("location");
    }


    public static double getDistance(String lonlat1,String lonlat2) {
        String urlString =DIS_URL+lonlat1+"&destination="+lonlat2; // 注意经纬度参数的顺序
        JSONObject responseJson = fetchJsonFromUrl(urlString);

        validateResponseStatus(responseJson);

        JSONArray resultsArray = responseJson.getJSONArray("results");
        if (resultsArray == null || resultsArray.isEmpty()) {
            throw new RuntimeException("计算距离失败，结果为空");
        }

        return Double.parseDouble(resultsArray.getJSONObject(0).getString("distance")) / 1000;
    }

    /**
     * 发送请求并返回JSON响应
     */
    private static JSONObject fetchJsonFromUrl(String serverUrl) {
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            StringBuilder jsonResponse = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    jsonResponse.append(inputLine);
                }
            }

            return JSONObject.parseObject(jsonResponse.toString());
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求失败", e);
        }
    }

    /**
     * 验证API响应状态是否成功
     */
    private static void validateResponseStatus(JSONObject responseJson) {
        if (!SUCCESS_FLAG.equals(responseJson.getString("status"))) {
            throw new RuntimeException("请求失败，错误码：" + responseJson.getString("infocode"));
        }
    }

    public double distance(String latlon) {
         return GaodeUtils.getDistance(GaodeUtils.getLonAndLatByAddress(adressProperties.getAddress()),GaodeUtils.getLonAndLatByAddress(latlon));

    }
}
